<?php 
	
	/**
	 * logout
	 */
	$app->post('/logout', function () use ($app) {
		setcookie("email", "", 1);
		setcookie("authorization", "", 1);
		session_unset();
		session_destroy();
	});
	
	/**
	 * login
	 */
	$app->post('/login', function () use ($app, $db) {
		if( $_COOKIE["email"] && $_COOKIE["authorization"] )
		{
			$email = $_COOKIE["email"];
			$authorization = $_COOKIE["authorization"];
		}
		else if( $_POST["email"] && $_POST["password"] )
		{
			$email = $_POST["email"];
			$password = $_POST["password"];
			$authorization = hash('sha512',$password);
			setcookie("email", $email);
			setcookie("authorization", $authorization);
		}
		$user = validate($email, $authorization);
		if($user)
		{
			$_SESSION['user'] = $user;
			$app->response()->header("Content-Type", "application/json");
			echo json_encode( $user );
		}
		else 
		{
			$app->halt(401);
		}

	});
	
	/**
	 * validate
	 */
	function validate($email, $authorization) {
		global $db;
		$user = $db->user()->where("email",$email)->fetch();
		$user = array (
			"id" => $user["id"],
			"name" => $user["name"],
			"email" => $user["email"],
			"password" => $user["password"],
			"companyId" => $user["companyId"]
		);
		$password = $user['password'];
		if($authorization == hash('sha512',$password))
		{
			return $user;
		}
	}
	
	/**
	 * authorize
	 */
	function authorize($role = "user") {
		return function () use ( $role ) {
			$app = \Slim\Slim::getInstance();
			if(!empty($_SESSION['user'])) {
				return true;
				/*
				if($_SESSION['user']['role'] == $role || $_SESSION['user']['role'] == 'admin') {
					return true;
				}
				else {
					$app->halt(403);
				}
				*/
			}
			else {
				$app->halt(401);
			}
		};
	}

?>
